<template>
  <view>
    <view class="wrapper">
      <view class="handBtn">
        <button @click="retDraw" class="delBtn">重写</button>
        <button @click="saveCanvasAsImg" class="saveBtn">保存</button>
      </view>
      <view class="handCenter">
        <canvas
          class="handWriting"
          :disable-scroll="true"
          @touchstart="uploadScaleStart"
          @touchmove="uploadScaleMove"
          canvas-id="handWriting"
        ></canvas>
      </view>
      <view class="handRight">
        <view class="handTitle">请签名</view>
      </view>
    </view>
    <!-- 伪全屏生成旋转图片canvas容器，不在页面上展示 -->
    <view
      style="
        position: fixed;
        left: -2000px;
        width: 0;
        height: 0;
        overflow: hidden;
      "
    >
      <canvas
        canvas-id="temp-tn-sign-canvas"
        :style="{ width: `${canvasHeight}px`, height: `${canvasHeight}px` }"
      ></canvas>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
const canvasName = ref("handWriting");
const ctx = ref();
const startX = ref();
const startY = ref();
const canvasWidth = ref(0);
const canvasHeight = ref(0);
const selectColor = ref("black");
const lineColor = ref("#1A1A1A");
const lineSize = ref(5);

function setCanvasBg(color: any) {
  /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
  //rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
  //这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
  ctx.value.rect(0, 0, canvasWidth.value, canvasHeight.value - 4);
  // ctx.setFillStyle('red')
  ctx.value.setFillStyle(color);
  ctx.value.fill(); //设置填充
  ctx.value.draw(); //开画
}
// 笔迹开始
function uploadScaleStart(e: any) {
  startX.value = e.touches[0].x;
  startY.value = e.touches[0].y;
  //设置画笔参数
  //画笔颜色
  ctx.value.setStrokeStyle(lineColor.value);
  //设置线条粗细
  ctx.value.setLineWidth(lineSize.value);
  //设置线条的结束端点样式
  ctx.value.setLineCap("round"); //'butt'、'round'、'square'
  //开始画笔
  ctx.value.beginPath();
}

// 笔迹移动
function uploadScaleMove(e: any) {
  //取点
  let temX = e.touches[0].x;
  let temY = e.touches[0].y;
  //画线条
  ctx.value.moveTo(startX.value, startY.value);
  ctx.value.lineTo(temX, temY);
  ctx.value.stroke();
  startX.value = temX;
  startY.value = temY;
  ctx.value.draw(true);
}

//重写
function retDraw() {
  ctx.value.clearRect(0, 0, 700, 730);
  ctx.value.draw();
  //设置canvas背景
  setCanvasBg("#fff");
}

//生成图片
function saveCanvasAsImg() {
  uni.canvasToTempFilePath({
    canvasId: "handWriting",
    fileType: "png",
    quality: 1, //图片质量
    success(res) {
      //console.log("canvas生成图片地址", res.tempFilePath);
      getRotateImage(res.tempFilePath)
        .then((res) => {
          uni.$emit("sign", res);
          uni.navigateBack({
            delta: 1,
          });
        })
        .catch((err) => {
          console.log("旋转图片失败");
        });
    },
  });
}

async function getRotateImage(dataUrl: any) {
  // const url = await this.base64ToPath(dataUrl)
  const url = dataUrl;

  // 创建新画布
  const tempCtx = uni.createCanvasContext("temp-tn-sign-canvas");
  const width = canvasWidth.value;
  const height = canvasHeight.value;
  tempCtx.restore();
  tempCtx.save();
  tempCtx.translate(0, height);
  tempCtx.rotate((270 * Math.PI) / 180);
  tempCtx.drawImage(url, 0, 0, width, height);
  tempCtx.draw();
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      uni.canvasToTempFilePath({
        canvasId: "temp-tn-sign-canvas",
        fileType: "png",
        x: 0,
        y: height - width,
        width: height,
        height: width,
        success: (res) => resolve(res.tempFilePath),
        fail: reject,
      });
    }, 50);
  });
}

onLoad((options: any) => {
  ctx.value = uni.createCanvasContext("handWriting");
  nextTick(() => {
    uni
      .createSelectorQuery()
      .select(".handCenter")
      .boundingClientRect((rect) => {
        canvasWidth.value = rect.width;
        canvasHeight.value = rect.height;
        /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
        setCanvasBg("#fff");
      })
      .exec();
  });
});
</script>

<style lang="scss" scoped>
page {
  background: #fbfbfb;
  height: auto;
  overflow: hidden;
}

.wrapper {
  width: 100%;
  height: 95vh;
  margin: 30rpx 0;
  overflow: hidden;
  display: flex;
  align-content: center;
  flex-direction: row;
  justify-content: center;
  font-size: 28rpx;
}

.handWriting {
  background: #fff;
  width: 100%;
  height: 95vh;
}

.handRight {
  display: inline-flex;
  align-items: center;
}

.handCenter {
  border: 4rpx dashed #e9e9e9;
  flex: 5;
  overflow: hidden;
  box-sizing: border-box;
}

.handTitle {
  transform: rotate(90deg);
  flex: 1;
  color: #666;
}

.handBtn button {
  font-size: 28rpx;
}

.handBtn {
  height: 95vh;
  display: inline-flex;
  flex-direction: column;
  justify-content: space-between;
  align-content: space-between;
  flex: 1;
}

.delBtn {
  position: absolute;
  top: 300rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #ffffff;
  background: red;
}

.delBtn image {
  position: absolute;
  top: 13rpx;
  left: 25rpx;
}

.subBtn {
  position: absolute;
  bottom: 52rpx;
  left: -3rpx;
  display: inline-flex;
  transform: rotate(90deg);
  background: #008ef6;
  color: #fff;
  margin-bottom: 30rpx;
  text-align: center;
  justify-content: center;
}

/*Peach - 新增 - 保存*/

.saveBtn {
  position: absolute;
  top: 775rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #fff;
  background: #008ef6;
}

.uploadBtn {
  position: absolute;
  top: 625rpx;
  left: 0rpx;
  transform: rotate(90deg);
  color: #666;
}

/*Peach - 新增 - 保存*/

.black-select {
  width: 60rpx;
  height: 60rpx;
  position: absolute;
  top: 30rpx;
  left: 25rpx;
}

.black-select.color_select {
  width: 90rpx;
  height: 90rpx;
  top: 100rpx;
  left: 10rpx;
}

.red-select {
  width: 60rpx;
  height: 60rpx;
  position: absolute;
  top: 140rpx;
  left: 25rpx;
}

.red-select.color_select {
  width: 90rpx;
  height: 90rpx;
  top: 120rpx;
  left: 10rpx;
}
</style>
